package shapes.shapes2D.distribution.tiling 
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Rectangle;
	import shapes.shapes2D.Quad;
	
	/**
	 * @author Nicolas Barradeau
	 * http://en.nicoptere.net
	 */
	public class MapLogic extends Sprite
	{
		
		private var _map:Array = [];
		private var gridW:int;
		private var gridH:int;
		private var tileMax:int;
		
		private var tileScale:int = 10;
		private var lookupDistance:int = 250;
		private var emptyPos:int = 0;
		
		public function MapLogic( gridW:int, gridH:int, tileMax:int, tileScale:int ):void
		{
			
			this.gridW        = gridW;
			this.gridH        = gridH;
			this.tileMax        = tileMax;
			this.tileScale    = tileScale;
			
		}
		
		public function create():Tile
		{
			
			var position:int = -1;
			var emptyWidth:int = 0;
			
			var i:int, j:int;
			for ( i = emptyPos; i < emptyPos + lookupDistance ; i++ )
			{
				
				if ( !_map[i] && position == -1 )
				{
					position = i;
					emptyWidth++;
				} 
				else if ( emptyWidth >= tileMax )
				{
					break;
				} 
				else if ( !_map[i] && !( i % gridW == 0 && i != emptyPos ) ) 
				{
					emptyWidth++;
				}
				else if ( position != -1 ) 
				{
					break;
				}
				
			}
			var ww:int = int( Math.random() * emptyWidth )+1;
			
			var p:int = position;
			for ( i = 0; i < ww; i++ )
			{
				for ( j = 0; j < ww; j++ )
				{
					_map[ p ] = 1;
					p++;
				}
				p += gridW - ww;
			}
			
			emptyPos = position + ww;
			
			var px:int = position % gridW * tileScale;
			var py:int = position == 0 ? 0 : int( position / gridW ) * tileScale;
			
			return new Tile( px, py, ww * tileScale, ww * tileScale );
			
		}
		
		public function start():void
		{
			addEventListener( Event.ENTER_FRAME, render );
        }
        
		public function stop():void
		{
			removeEventListener( Event.ENTER_FRAME, render );
        }
        
        private function render( e:Event ):void
        {
            addChild( create() );
        }
		
	}

}

import flash.display.Shape;
internal class Tile extends Shape
{
    public function Tile( _x:int, _y:int, _w:int, _h:int ):void
    {
        this.x = _x;
        this.y = _y;
        
        graphics.lineStyle( 1, 0x000000 );
        graphics.beginFill( 0xFFFFFF );
        graphics.drawRect( 0, 0, _w, _h );
    }
}